package com.example.dmallOrder.common.dmall.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *  自定义http请求工具
 *
 * @author:yanbo.li
 * @date: 2023/3/18
 */
public class HttpUtil {
    private static String POST = "POST";
    private static String GET = "GET";
    private static String CONTENT_TYPE_URLENCODED = "application/x-www-form-urlencoded";
    private static String CONTENT_TYPE_JSON = "application/json";

    private static String httpRequest(String method, String contentType, String urlStr, Map<String, String> paras)
            throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


        if (paras != null && !paras.isEmpty()) {
            con.setDoOutput(true);
            DataOutputStream out = new DataOutputStream(con.getOutputStream());
            out.writeBytes(ParameterStringBuilder.getParamsString(paras));
            out.flush();
            out.close();
        }


        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer content = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine);
        }
        in.close();
        con.disconnect();


        return content.toString();
    }

    private static class ParameterStringBuilder {
        public static String getParamsString(Map<String, String> params)
                throws UnsupportedEncodingException {
            StringBuilder result = new StringBuilder();

            for (Map.Entry<String, String> entry : params.entrySet()) {
                result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                result.append("=");
                result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                result.append("&");
            }

            String resultString = result.toString();
            return resultString.length() > 0
                    ? resultString.substring(0, resultString.length() - 1)
                    : resultString;
        }
    }


    public static String httpGetRequest(String url) {
        try {
            return httpRequest(GET, CONTENT_TYPE_URLENCODED, url, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String httpPostRequest(String url, Map<String, String> paras) {
        try {
            return httpRequest(POST, CONTENT_TYPE_URLENCODED, url, paras);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 获得HttpPost对象
     *
     * @param url    请求地址
     * @param params 请求参数
     * @param encode 编码方式
     * @return HttpPost对象
     * @throws UnsupportedEncodingException
     */
    public static HttpPost getHttpPost(String url, Map<String, Object> params,
                                        String encode ,Map<String,String> headers) throws UnsupportedEncodingException, URISyntaxException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", CONTENT_TYPE_URLENCODED);

        for (String name : headers.keySet()) {
            httpPost.addHeader(name, headers.get(name));
        }

        if (params != null) {
            List<NameValuePair> form = new ArrayList<NameValuePair>();
            for (String name : params.keySet()) {
                form.add(new BasicNameValuePair(name, params.get(name)==null?"":params.get(name).toString()));
            }

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
                    encode);
            httpPost.setEntity(entity);
        }

        return httpPost;

    }
}
